package com.xunmall.account.interceptor;

import com.xunmall.account.service.impl.JCaptchaServiceImpl;
import com.xunmall.base.exception.BadRequestException;
import com.xunmall.base.exception.BaseException;
import com.xunmall.base.exception.BusinessException;
import com.xunmall.base.logger.ErrorLogInfo;
import com.xunmall.base.util.WebUtils;
import com.xunmall.security.GlobalSessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
public class JCaptchaValidateFilter implements Filter {
    /**
     * 初始化
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(final FilterConfig filterConfig) throws ServletException {
        // left blank intentionally
    }

    /**
     * 过滤
     *
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain filterChain)
            throws IOException, ServletException {
        String clientId = req.getParameter("client_id");
        String servletPath = ((HttpServletRequest) req).getServletPath();
        if (!GlobalSessionUtil.isAppLogin(clientId) && ("/oauth/token".equals(servletPath))) {
            String username = req.getParameter("username");
            if (username == null) {
                BadRequestException bex = new BadRequestException("error.gateway.0001", this);
                WebUtils.sendJsonError((HttpServletRequest) req, (HttpServletResponse) res, bex, HttpStatus.BAD_REQUEST);
                return;
            }

            String remoteAddr = WebUtils.getRemoteAddr((HttpServletRequest) req);
            String sessionId = remoteAddr;//remoteAddr.concat(":").concat(username);
            // 1、检查验证码是否开启
            Boolean jcaptchaEbabled = JCaptchaServiceImpl.getJcaptchaEbabled(sessionId);
            ((HttpServletResponse) res).setHeader("jcaptchaNeed", jcaptchaEbabled.toString());
            // 2、开启验证码
            if (jcaptchaEbabled) {
                String jcaptchaId = req.getParameter("jcaptchaId");
                if (jcaptchaId == null) {
                    BadRequestException bex = new BadRequestException("mark you code!", this);
                    WebUtils.sendJsonError((HttpServletRequest) req, (HttpServletResponse) res, bex, HttpStatus.BAD_REQUEST);
                    return;
                }
                String jcaptchaCode = req.getParameter("jcaptchaCode");
                if (jcaptchaCode == null) {
                    BadRequestException bex = new BadRequestException("error.gateway.0002", this);
                    WebUtils.sendJsonError((HttpServletRequest) req, (HttpServletResponse) res, bex, HttpStatus.BAD_REQUEST);
                    return;
                }
                // 3、验证验证码是否正确
                if (!JCaptchaServiceImpl.validateCaptcha(jcaptchaId, jcaptchaCode)) {
                    // 如果验证码失败了
                    try {
                        BadRequestException bex = new BadRequestException("error.0004", this);
                        log.error(ErrorLogInfo.build(this, "captcha", bex.getErrorCode(), bex.getMessage()).toJson());
                        WebUtils.sendJsonError((HttpServletRequest) req, (HttpServletResponse) res, bex, HttpStatus.BAD_REQUEST);
                        return;
                    } catch (Exception e1) {
                        WebUtils.sendJsonError((HttpServletRequest) req, (HttpServletResponse) res, new BusinessException(BaseException.ERR_9999, e1, this), HttpStatus.BAD_REQUEST);
                        return;
                    }
                }
            }
        }

        filterChain.doFilter(req, res);
    }

    /**
     * do nothing
     */
    @Override
    public void destroy() {
        // left blank intentionally
    }
}